<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Field;
use App\Models\Booking;
use App\Models\BookingField;
use App\Models\System;
use App\Services\Wechat;
use App\Services\AliSms;
use App\Services\RedisService;



class BookingController extends Controller
{
    public function index(Request $request)
    {
        $system = System::first();
        $fields = Field::where(['status'=>1])->get();
    	return view('booking.index',compact('fields','system'));
    }

    public function save(Request $request)
    {   
        $rs['status'] = 'danger';
        $mobile = $request->mobile;
        $system = System::first();
        //dd($system);
        if($system->is_sms) {
            $code = RedisService::get('booking:sms:'.$mobile);
            if($code!=$request->validatecode){
                $rs['msg'] = '短信验证码错误';            
                return back()->withInput()->with('rs',$rs);
            }    
        }
        

        $task['code']   = date('YmdHis').mt_rand(10,99);
        $wechat_user    = session('wechat.oauth_user.default');   
        //dd($wechat_user);  
        $task['openid'] = $wechat_user->id;
        $task['mobile'] = $mobile;
        $t = Booking::create($task);
        $fields = $request->fields;
        dd($fields);
        $msg = [];
        foreach ($fields as $k => $v) {
            $field_id = $k;
            $field    = Field::find($field_id);
            $data['booking_id'] = $t->id;
            $data['field_id']   = $field_id;
            $data['field_name'] = $field->name;
            $data['value'] = $v;
            $msg[$field->name] = $v;
            BookingField::create($data);
        }

        $rs['status'] = 'success';
        $rs['msg'] = '预约成功';

        // 推送模板
        // 推送消息给提交者
        $msg['openid']     = $t->openid;
        $msg['mobile']     = $mobile;
        $msg['created_at'] = date('Y-m-d H:i:s');      
        $msg['remark'] = '';    
        $msg['url']    = '';   

        Wechat::sendMsgTpl('new_to_user',$msg);

        return back()->with('rs',$rs);
    }

    public function sendMsg(Request $request)
    {
        $rs['status'] = false;
        $mobile = $request->mobile;
        if(strlen($mobile)!=11) {
            $rs['msg'] = '手机号码错误';
            return response()->json($rs);
        }
        $code   = mt_rand(1000,9999);
        RedisService::set('booking:sms:'.$mobile,$code);

        $rs =  AliSms::sendMsg($mobile,$code);
        
    }

   

    

   

    
}
